import React, {Component} from 'react';
import {findDOMNode} from 'react-dom';
import {Relax} from 'iflux2';
import {Map, List} from 'immutable';

import {Row, Col, Button, Popconfirm, Modal, Input, Timeline, Popover, Form, message} from 'antd';

const TimelineItem = Timeline.Item;
const FormItem = Form.Item;
import {Link} from 'react-router';
import {tipQL, currentQL} from '../ql';
import QMIcon from 'components/QmIcon';

import Deliver from '../../common/deliver';
import Receipt from '../../common/receipt';
import Timer from './timer';
import Refund from '../../common/refund';
import Image from 'components/Image';

import noop from 'util/noop';
import classNames from 'classnames';
import moment from 'moment';

import {tips} from '../constant/constant';
import { defaultAvatorImage } from 'constant/image.js'

@Relax
export default class OrderInfo extends Component {
    static defaultProps = {
        detail: Map(),
        expressCompany: List(),
        logistics: Map(),
        receiptList: List(),
        autoCancelTime: 0,
        autoConfirmTime: 0,
        afterSaleTime: 0,
        userLogo: '',
        tip: tipQL,
        current: currentQL,
        applyRefundAmount: 0,
        payAmount: 0,
        tradeOrder: Map(),
        payTypeBOList: List(),

        deliveryOrder: noop,
        completeOrder: noop,
        cancelOrder: noop,
        editSellerRemark: noop,
        setRemark: noop,
        saveReceipt: noop,
        modifyBuyerConsignee: noop,
        refundBefore: noop,
        refund: noop
    }


    constructor(props) {
        super(props);

        this.state = {
            visible: false,
            confirmLoading: false,
            completeLoading: false,
            cancelLoading: false,
            remark_visible: false,
            delivery_visible: false,
            logistics_visible: false,
            refund_visible: false,
            receipt_loading: false
        }
    }


    render() {
        const {tip, current, detail, expressCompany, setRemark, logistics, receiptList
            , payAmount, tradeOrder, payTypeBOList, autoCancelTime,
            autoConfirmTime, afterSaleTime, userLogo} = this.props;
        const {visible, confirmLoading, remark_visible, delivery_visible, logistics_visible, refund_visible,
            receiptId, receipt_loading} = this.state;

        const {consigneeAddress, consigneeCity, consigneeDistrict,
            consigneeMobile, consigneeName, consigneeProvince} = (detail.get('consigneeInfo') || Map()).toJS();

        const logisticsState = classNames({
            't-primary': current == 2 || current == 3,
            't-grayer': current != 2 && current != 3
        });

        let logisticsContent = null;
        if (current == 0) {
            logisticsContent = (<p className="lh24">买家付款后才可以发货</p>);
        } else if (current == 1) {
            logisticsContent = (<p className="lh24">还没有发货，请及时发货保证优质的客户体验~</p>);
        } else if (current == 2 || current == 3 || current == 4) {
            if (!logistics.get('data') || logistics.get('data').isEmpty()) {
                logisticsContent = (
                    <div>
                        <p className="lh24">暂无物流信息</p>
                    </div>
                )
            } else {
                logisticsContent = (
                    <div onClick={()=>this.info()}>
                        <p className="lh24"><a href="javascript:void(0);">{logistics.getIn(['data', 0, 'context'])}</a>
                            <span className="pull-right"><a href="javascript:void(0);" >物流跟踪</a></span></p>
                        <p className="t-grayer">{moment(logistics.getIn(['data', 0, 'time'])).format('YYYY-MM-DD HH:mm:ss')}</p>
                    </div>
                )
            }
        } else {
            logisticsContent = (<p className="lh24">交易已关闭</p>)
        }

        return (
            <div className="order-info">
                <Row className="order-info-hd">
                    <Col span={4}>
                        <div className="font-14">
                            <b>订单状态：</b><span className="t-red">{tip}</span>
                        </div>
                    </Col>
                    <Col span={14} className="lh22">
                        <div>
                            <Timer detail={detail}
                                   current={current}
                                   autoCancelTime={autoCancelTime}
                                   autoConfirmTime={autoConfirmTime}
                                   afterSaleTime={afterSaleTime}/>
                            <span className="t-grayer">{`${tips[current] || ''}`}</span>
                        </div>
                    </Col>
                    <Col span={6}>
                        <div className="t-right">
                            {
                                this.renderopts()
                            }
                        </div>
                    </Col>
                </Row>
                <Row className="order-info-bd">
                    <Col span={15}>
                        <ul className="info-item pr30 bdr">
                            <li className="bdb">
                                <QMIcon type="wuLiuGongSi" className={logisticsState}/>
                                {logisticsContent}
                            </li>
                            <li>
                                <QMIcon type="dizhi2" className="t-grayer"/>
                                <p className="lh24">
                                    {`配送方式：${detail.get('shipMethodName') || ''}`}
                                    <p>{`收货人：${consigneeName || ''}`} <span className="pushl">{`手机：${consigneeMobile || ''}`}</span></p>
                                    <span className="pull-right">
                                        {
                                            (current == 0 || current == 1)
                                                ? <a href="javascript:void(0);"
                                                     className="pushl"
                                                     onClick={()=>this.changeDeliveryVisible()}>修改地址</a> : null
                                        }
                                    </span>
                                </p>
                                <p>{`收货地址：${consigneeProvince || ''}${consigneeCity || ''} ${consigneeDistrict || ''} ${consigneeAddress || ''}`}</p>
                                {
                                    detail.get('shippingMethod') == 'SELF'
                                    ?
                                    this.renderSelfAddress(detail.get('consigneeInfo'))
                                    : null
                                }
                            </li>
                            <li>
                                <QMIcon type="fapiao" className="t-grayer"/>
                                <p className="lh24">
                                    {
                                        !!detail.get('invoiceName') ? `发票抬头：${detail.get('invoiceName')}` : '不开发票'
                                    }
                                    {
                                        detail.get('invoiceFlag') == 1
                                            ? detail.get('invoiceType') == 1 ? '(普通发票)' : '(增值税发票)'
                                            : ''
                                    }
                                    <span className="pull-right">
                                        {detail.get('invoiceFlag') == 1 && detail.get('invoiceType') == 2
                                            ?
                                            <Popover overlayClassName="w360"
                                                     placement="bottom"
                                                     content={this.renderInvoiceDetail(detail.get('invoice'))}><a href="javascript:void(0);">发票详情</a></Popover> : null}
                                    </span>
                                </p>
                            </li>
                        </ul>
                    </Col>
                    <Col span={9}>
                        <ul className="info-item pl30 bdl">
                            <li className="bdb">
                                <div className="avatar">
                                    <Image src={userLogo || defaultAvatorImage} auto={tradeOrder}/>
                                </div>
                                <p className="lh44">
                                    {`买家：${detail.get('buyNickName') || ''}`}
                                </p>
                                {
                                    !!detail.get('idCard')
                                        ? <p className="lh44">身份证号码：{detail.get('idCard')}</p> : null
                                }
                            </li>
                            <li>
                                <QMIcon type="liuyan" className="t-grayer"/>
                                <p className="lh24">买家留言：</p>
                                <p>{detail.get('tmark') || '暂无留言'}</p>
                            </li>
                            <li>
                                <QMIcon type="bianji" className="t-grayer"/>
                                <p className="lh24">卖家备注：
                                    <span className="pull-right">
                                        <a href="javascript:void(0)" onClick={()=>this.remarkVisible()}>修改备注</a>
                                    </span>
                                </p>
                                <p>{detail.get('sellerMark') || '暂无备注'}</p>
                            </li>
                        </ul>
                    </Col>
                </Row>
                <Deliver order={detail}
                         visible={visible}
                         confirmLoading={confirmLoading}
                         expressCompany={expressCompany}
                         onOk={(values)=>this.onOk(values)}
                         onCancel={()=>this.onCancel()}/>

                <Modal title="订单备注"
                       visible={remark_visible}
                       onOk={()=>this.editRemark()}
                       onCancel={()=>this.remarkVisible()}>
                    <Input type="textarea"
                           ref="remark"
                           value={detail.get('sellerMark')}
                           onChange={(e)=>setRemark(e.target.value)}
                           placeholder="请输入备注内容"
                           rows={8}
                           maxLength={200}/>
                </Modal>

                <Modal title="收货地址"
                       visible={delivery_visible}
                       width="620"
                       confirmLoading={receipt_loading}
                       maskClosable={false}
                       onOk={()=>this.saveReceipt()}
                       onCancel={()=>this.setState({delivery_visible: false})}>
                    <div className="pushl">
                        {
                            receiptList.map((item, index)=>{
                                let {province, city, area, detailAddress, receiptUserName, phone} = this.spiltArea(item.toJS());
                                return (
                                    <div key={index} className="pushb">
                                        <input type="radio"
                                               checked={item.get('receiptId') == receiptId}
                                               name="receipt"
                                               className="mr3"
                                               onClick={()=>this.changeReceipt(item.get('receiptId'))}/>
                                        <span className="pushl">{receiptUserName}</span>
                                        <span className="pushl">{`${province} ${city} ${area}`}</span>
                                        <span className="pushl">{detailAddress}</span>
                                        <span className="pushl">{phone}</span>
                                    </div>
                                )
                            })
                        }
                        {
                            receiptList.count() < 10
                                ?   <div key='new' className="pushb">
                                        <input type="radio"
                                               checked={receiptId == 'add'}
                                               name="receipt"
                                               className="mr3"
                                               onClick={()=>this.changeReceipt('add')}/>
                                        <span>新增收货地址</span>
                                    </div>
                                : null
                        }
                        {
                            receiptId == 'add' ? <Receipt ref="receipt"/> : null
                        }
                    </div>
                </Modal>


                <Modal title="物流信息"
                       footer={null}
                       width="600"
                       visible={logistics_visible}
                       onCancel={()=>this.setState({logistics_visible: false})}>
                    <div>
                        <div className="pushb ml30">
                            <span>物流公司：{logistics.get('company')}</span>
                            <span className="ml120">物流单号：{logistics.get('nu')}</span>
                        </div>
                        <div className="pushtt ml30">
                            <Timeline>
                                {
                                    (logistics.get('data') || List()).map((item, index)=>{
                                        return (
                                            <TimelineItem key={index}>
                                                <div>{item.get('context')}</div>
                                                <div>{moment(item.get('time')).format('YYYY-MM-DD HH:mm:ss')}</div>
                                            </TimelineItem>
                                        )
                                    }).toArray()
                                }
                            </Timeline>
                        </div>
                    </div>
                </Modal>

                <Refund payAmount={payAmount}
                        tradeOrder={tradeOrder}
                        payTypeBOList={payTypeBOList}
                        visible={refund_visible}
                        showModal={this.showRefundModal}
                        onOk={this.reimburse}/>
            </div>
        )
    }


    renderSelfAddress(consigneeInfo) {
        const {selfPickupAddress, selfPickupName, selfPickupPhone} = consigneeInfo.toJS();

        return (
            <p>自提点地址：{selfPickupName || ''}，{selfPickupAddress}，{selfPickupPhone}</p>
        )
    }


    renderInvoiceDetail(invoice) {
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 20 },
        };

        return (
            <div>
                <Form>
                    <FormItem
                        label="银行"
                        {...formItemLayout}><p>{invoice.get('invoiceBank')}</p></FormItem>
                    <FormItem
                        label="账号"
                        {...formItemLayout}><p>{invoice.get('invoiceAccount')}</p></FormItem>
                    <FormItem
                        label="地址"
                        {...formItemLayout}><p>{invoice.get('invoiceAddress')}</p></FormItem>
                    <FormItem
                        label="名称"
                        {...formItemLayout}><p>{invoice.get('invoiceName')}</p></FormItem>
                    <FormItem
                        label="税号"
                        {...formItemLayout}><p>{invoice.get('invoiceUserId')}</p></FormItem>
                </Form>
            </div>
        )
    }


    info() {
        const {logistics} = this.props;
        if (!logistics.isEmpty() && !logistics.get('data').isEmpty()) {
            this.setState({
                logistics_visible: true
            })
        }
    }


    changeReceipt(receiptId) {
        this.setState({receiptId});
    }


    /**
     * 操作渲染
     * @returns {Array}
     */
    renderopts() {
        const {detail} = this.props;
        const orderStatus = detail.get('orderStatus');
        let opts = [];
        if (orderStatus === 'WAIT_PAY') {
            opts.push(<Link to={`/order/edit/unpay/${this.props.detail.get('tid')}`}><Button type="ghost" className="pushl">修改</Button></Link>);
            opts.push(<Popconfirm placement="topLeft"
                                  title="确定取消订单吗？"
                                  onConfirm={()=>this.cancelOrder()}>
                <Button type="ghost" className="pushl">取消</Button></Popconfirm>);
        } else if (orderStatus === 'WAIT_DELIVER') {
            if (detail.get('payTypeId') === 'GRP') {
                opts.push( <Popconfirm placement="topLeft"
                                       title="确定取消订单吗？"
                                       onConfirm={()=>this.cancelOrder()}>
                    <Button type="ghost" className="pushl">取消</Button></Popconfirm>);
            } else {
                opts.push( <Button type="ghost" className="pushl" onClick={()=>this.refund()}>申请退款</Button>);
            }

            detail.get('deliverable') && opts.push(<Button type="primary" className="pushl" onClick={()=>this.deliver()}>发货</Button>);
        } else if (orderStatus === 'SUCCESS' && detail.get('isApplyReturn') == 1 && detail.get('applyState') == '0') {
            opts.push( <Link to={`/after/sales/${this.props.detail.get('tid')}`}><Button type="ghost" className="pushl">代客退货</Button></Link>);
        } else if (orderStatus == 'WAIT_RECEIVE') {
            detail.get('payTypeId') !== 'GRP'
            &&opts.push( <Button type="ghost"
                               className="pushl"
                               loading={this.state.completeLoading}
                               onClick={()=>this.completeOrder()}>完成</Button>);
        }
        return opts;
    }

    refund = ()=>{
        const _this = this;
        const {detail, refundBefore} = _this.props;
        refundBefore(detail.get('tid')).then(()=>{
            _this.showRefundModal(true);
        });
    }


    reimburse = (params)=>{
        return this.props.refund(params);
    }


    showRefundModal = (visible)=>{
        this.setState({
            refund_visible: visible
        })
    }


    /**
     * 发货
     */
    deliver() {
        this.setState({
            visible: true
        })
    }

    /**
     * 发货操作
     * @param values
     */
    onOk(values) {
        this.setState({confirmLoading: true});
        this.props.deliveryOrder(values).then(()=>{
            this.setState({
                    visible: false,
                    confirmLoading: false});
        }).catch(err=>{
            this.setState({
                    confirmLoading: false
                });
        });
    }


    saveReceipt() {
        const {modifyBuyerConsignee, detail, saveReceipt} = this.props;
        const {receiptId, receipt_loading} = this.state;

        if (!receiptId) {
            message.warn('请选择收货地址');
            return ;
        }


        if (receiptId == 'add') {
            this.refs.receipt.validateFields((errors, values)=>{
                if (!errors) {
                    this.setState({
                        receipt_loading: true
                    });
                    let {cascader:[province, city, area], ...rest} = values;

                    saveReceipt(Object.assign({}, rest, {
                        province,
                        city,
                        area
                    })).then((data)=>{
                        modifyBuyerConsignee({
                            tid: detail.get('tid'),
                            consigneeId: data
                        }).then(()=>{
                            this.setState({
                                delivery_visible: false,
                                receipt_loading: false,
                                receiptId: data
                            })
                        })
                    })
                }
            }).catch(()=>{
                this.setState({
                    receipt_loading: false
                })
            })
        } else if (!!receiptId) {
            this.setState({
                receipt_loading: true
            });
            modifyBuyerConsignee({
                tid: detail.get('tid'),
                consigneeId: receiptId
            }).then(()=>{
                this.setState({
                    delivery_visible: false,
                    receipt_loading: false
                })
            }).catch(()=>{
                this.setState({
                    receipt_loading: false
                })
            })
        }
    }


    /**
     * 取消
     */
    onCancel() {
        this.setState({visible: false})
    }


    /**
     * 完成订单
     */
    completeOrder() {
        const {completeOrder, detail} = this.props;
        this.setState({
            completeLoading: true
        });
        completeOrder(detail.get('tid')).then(()=>{
            this.setState({
                completeLoading: false
            });
        }).catch(()=>{
            this.setState({
                completeLoading: false
            });
        })
    }


    /**
     * 取消订单
     */
    cancelOrder() {
        const {cancelOrder, detail} = this.props;

        this.setState({
            cancelLoading: true
        });

        cancelOrder(detail.get('tid')).then(()=>{
            this.setState({
                cancelLoading: false
            });
        }).catch(()=>{
            this.setState({
                cancelLoading: false
            });
        })
    }


    /**
     * 修改备注
     */
    remarkVisible() {
        this.setState({
            remark_visible: !this.state.remark_visible
        });
    }


    editRemark() {
        const {editSellerRemark, detail} = this.props;
        let remark = (detail.get('sellerMark') || "").trim();

        if (!!remark) {
            editSellerRemark({
                tid: detail.get('tid'),
                remark
            }).then(()=>{
                this.setState({
                    remark_visible: false
                })
            })
        }else {
            message.warn('备注内容不能为空');
        }
    }


    changeDeliveryVisible() {
        this.setState({
            delivery_visible: true
        })
    }


    spiltArea(receipt) {
        const {province, city, area, detailAddress, mobilePhone, receiptUserName, ...rest} = receipt;

        return {
            province: province.split('-')[1],
            city: (city || '-').split('-')[1],
            area: (area || '-').split('-')[1],
            detailAddress,
            receiptUserName,
            phone: mobilePhone || rest.fixPhone
        }
    }
}